package net.flydy.ywxcx.wxcloudrun.config;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import net.flydy.ywxcx.wxcloudrun.common.StatusEnum;
import net.flydy.ywxcx.wxcloudrun.vo.BaseResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class AdminLoginInterceptor implements HandlerInterceptor {

    private void responseJson(HttpServletResponse response, String jsonStr) throws Exception{
        //更改response的默认吗表为gbk
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonStr);
        writer.flush();
    }

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
//        try {
////            response.sendRedirect(request.getContextPath() + "login");
//            BaseResponse baseResponse = new BaseResponse(StatusEnum.TOKEN_BAD);
//            baseResponse.setReqNo("bad");
//            baseResponse.setMessage("no login");
//            responseJson(response, JSONUtil.toJsonPrettyStr(baseResponse));
//            response.flushBuffer();
//            return false;
//        } catch (Exception e) {
//            log.error("", e);
//        }
        return true;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("执行了拦截器的afterCompletion方法");
    }
}
